package com.hsy.swu.login

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.hsy.swu.HomeActivity
import com.hsy.swu.clouddb.LeanCloudHelper
import com.hsy.swu.clouddb.MyUser
import com.hsy.swu.clouddb.MyUser.Companion.USER_INFO
import com.hsy.swu.databinding.ActivityLoginBinding
import com.hsy.swu.hsyutils.HsyActivity
import com.hsy.swu.hsyutils.HsyViewModel
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.hsyutils.MLog
import com.hsy.swu.version.Updater
import com.hsy.swueasspider.ui.SwuEasSpiderActivity
import com.kongzue.dialogx.dialogs.MessageDialog

class LoginActivity : HsyActivity<ActivityLoginBinding, HsyViewModel>() {
    private val loginRequestCode = 10000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setTvTipClick()
        setLoginButtonClick()

        checkIsHaveUser(this@LoginActivity)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == loginRequestCode && resultCode == RESULT_OK) {
            val msg = if (data?.getBooleanExtra(
                    SwuEasSpiderActivity.IS_GET_COOKIE_SUCCEED,
                    false
                ) == true
            ) {
                MyUser.currentUser.let {
                    it.account = mBinding.account.text.toString()
                    it.password = mBinding.password.text.toString()
                }
                cloudDBCheck(mBinding.account.text.toString())
                MyUser.currentUser.writeFirst4ToSp(this, USER_INFO)
                startActivity(Intent(this@LoginActivity, HomeActivity::class.java).apply {
                    putExtra("isButtonLogin", true) // 是通过登录按键登录而不是通过读取 sp
                })
                finish()
                "登录成功"
            } else {
                "登录失败，账号密码或验证码输入错误"
            }

            MActivityUtil.showToast(msg)
        }
    }

    /** 检查是否缓存了账号和密码，如果缓存了，就直接登 */
    private fun checkIsHaveUser(activity: AppCompatActivity) {
        MyUser.currentUser.readFirst4FromSp(activity, USER_INFO)
        // 当 sp 里存了用户名和密码就不去网络登录，直接登要不然每次打开都要登录会卡，之后刷新的时候才做账号密码校验
        MLog.v("check -> ${MyUser.currentUser.objectId}\t${MyUser.currentUser.account}\t${MyUser.currentUser.password}\t${MyUser.currentUser.nickName}")
        if (MyUser.currentUser.account != "" && MyUser.currentUser.password != "") {
            MLog.attention("直接登录")
            cloudDBCheck(MyUser.currentUser.account)
            startActivity(Intent(this@LoginActivity, HomeActivity::class.java).apply {
                putExtra("isButtonLogin", false)
            })
            finish()
        } else {
            // sp 中没账号密码就就展示通告
            mBinding.tvTip.callOnClick()

            Updater(this).apply {
                if (checkIsNeedUpdate()) {
                    showUpdateDialog(true)
                }
            }
        }
    }

    private fun setTvTipClick() {
        mBinding.tvTip.setOnClickListener {
            MessageDialog.build()
                .setTitle("强烈建议❗❗❗")
                .setMessage("使用此 App期间断开校园wifi，仅使用移动数据，可以大大提升刷新数据速度!!!")
                .show()
        }
    }

    private fun setLoginButtonClick() {
        mBinding.btnLogin.setOnClickListener {
            login(
                mBinding.account.text.toString(),
                mBinding.password.text.toString()
            )
        }
    }

    private fun login(
        username: String,
        password: String,
    ) {
        if (username.isEmpty() || password.isEmpty()) {
            MActivityUtil.showToast("请输入账号及密码")
            return
        }

        MActivityUtil.showToast("正在登录")

        val intent = Intent(this, SwuEasSpiderActivity::class.java)
            .putExtra(SwuEasSpiderActivity.MODE, SwuEasSpiderActivity.MODE_GET_COOKIE)
            .putExtra(SwuEasSpiderActivity.USERNAME, username)
            .putExtra(SwuEasSpiderActivity.PASSWORD, password)
        startActivityForResult(intent, loginRequestCode)
    }

    private fun cloudDBCheck(account: String) {
        LeanCloudHelper.getInstance()?.findObjectInBackground(
            "MyUser",
            { it.whereEqualTo("account", account) }
        ) { lcObjectList ->
            if (lcObjectList.isEmpty()) {
                // 如果没找到用户，就注册
                LeanCloudHelper.getInstance()?.saveObjectInBackground(
                    "MyUser",
                    {
                        MyUser.currentUser.objectId = it.objectId
                        it.put("account", account)
                        return@saveObjectInBackground it
                    },
                    { MLog.attention("注册失败：$it") }
                ) {}
            } else if (lcObjectList.size == 1) {
                MLog.v("用户已存在")
                LeanCloudHelper.getInstance()?.updateObjectInBackground(
                    "MyUser",
                    lcObjectList[0].objectId,
                    { MLog.attention("nickName更新失败：$it") },
                    {
                        MyUser.currentUser.objectId = lcObjectList[0].objectId
                        it.put("version", packageManager.getPackageInfo(packageName, 0).versionName)
                        if (lcObjectList[0].get("nickName") == null || lcObjectList[0].get("nickName") == "") {
                            it.put("nickName", MyUser.currentUser.nickName)
                        } else {
                            val submission = lcObjectList[0].get("submission")
                            MLog.attention("isAlreadySubmit -> $submission")
                            if (submission == null) {
                                LeanCloudHelper.tempIsNeedShowSubmitDialog = true
                                LeanCloudHelper.tempSubmission = ""
                            } else {
                                LeanCloudHelper.tempSubmission = submission.toString()
                                MLog.attention("tempSubmission->${LeanCloudHelper.tempSubmission}")
                            }
                        }
                    }
                )
            }
            MyUser.currentUser.writeFirst4ToSp(this, USER_INFO)
        }
    }
}